<template>
    <div class="overview">
        <div class="row">
            <div class="col-md-3">
                <div class="panel panel-theme" style="position: relative;">
                    <h3 class="panel-heading">Market Grade</h3>
                    <div class="panel-body">
                        <ul class="country-state" style="position: relative;">
                            <loading :show='loading'></loading>
                            <li>
                                <small>Rental Demand</small>
                                <div class="pull-right">{{MarketGrade.RentalDemand}}</div>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="50"
                                         aria-valuemin="0" aria-valuemax="100"
                                         :style="{'width': MarketGrade.RentalDemand}"></div>
                                </div>
                            </li>
                            <li>
                                <small>Revenue Growth</small>
                                <div class="pull-right">{{MarketGrade.RevenueGrowth}}</div>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-inverse" role="progressbar" aria-valuenow="50"
                                         aria-valuemin="0" aria-valuemax="100"
                                         :style="{'width': MarketGrade.RevenueGrowth}"></div>
                                </div>
                            </li>
                            <li>
                                <small>Seasonality</small>
                                <div class="pull-right">{{MarketGrade.Seasonality}}</div>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="50"
                                         aria-valuemin="0" aria-valuemax="100"
                                         :style="{'width': MarketGrade.Seasonality}"></div>
                                </div>
                            </li>
                            <li>
                                <small>Booking Leads Time</small>
                                <div class="pull-right">{{MarketGrade.bookingLeadsTime}}</div>
                                <div class="progress">
                                    <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="50"
                                         aria-valuemin="0" aria-valuemax="100"
                                    ></div>
                                </div>
                            </li>
                        </ul>
                    </div>

                </div>
                <div class="panel panel-primary" style="position: relative;">
                    <div class="panel-heading">
                       Active Rentals
                    </div>
                    <div class="panel-body">
                        <loading :show='loading'></loading>
                        <chart type="bar" title="Rental Type" :y="ActiveRental.data"
                                className="ActiveRental" v-if="ActiveRental.data" ></chart>
                    </div>
                </div>
                <div class="panel panel-success" style="position: relative;">
                    <h3 class="panel-heading">Rental Size</h3>
                    <div class="panel-body">
                        <loading :show='loading'></loading>
                        <chart :x="RentalSize.x" :y="RentalSize.y" className="RentalSize" title=""
                               type="column"></chart>
                    </div>

                </div>
                <div class="panel panel-info" style="position: relative;">
                    <h3 class="panel-heading">{{ActiveHost.total}} Active Host</h3>
                    <div class="panel-body">
                        <loading :show='loading'></loading>
                        <chart type="bar" title="Host Type" :y="ActiveHost.y"
                               :x="['Super Host', 'Single listing Host', 'Multiple Listing Host']" className="ActiveHost"></chart>
                    </div>
                </div>
            </div>
            <div class="col-md-9">
                <div class="row">
                    <div class="col-md-4">
                        <div class="white-box" style="position: relative;">
                            <loading :show="loading"></loading>
                            <div class="row">
                                <div class="col-sm-6">
                                    <h2 class="m-b-0 font-medium">¥{{AverageDailyRate}}</h2>
                                    <h5 class="text-muted m-t-0">Average Daily Rate</h5>
                                </div>
                                <div class="col-sm-6">
                                    <div>
                                        <i class="ti-bar-chart text-success" style="font-size: 90px;"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="white-box" style="position: relative;">
                            <loading :show="loading"></loading>
                            <div class="row">
                                <div class="col-sm-6">
                                    <h2 class="m-b-0 font-medium">{{AccupancyRate}}%</h2>
                                    <h5 class="text-muted m-t-0">Occupancy Rate</h5>
                                </div>
                                <div class="col-sm-6">
                                    <div>
                                        <i class=" ti-stats-up text-info" style="font-size: 90px;"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="white-box" style="position: relative;">
                            <loading :show="loading"></loading>
                            <div class="row">
                                <div class="col-sm-6">
                                    <h2 class="m-b-0 font-medium">¥{{Revence}}</h2>
                                    <h5 class="text-muted m-t-0">Revenue</h5>
                                </div>
                                <div class="col-sm-6">
                                    <div>
                                        <i class="ti-pie-chart text-primary" style="font-size: 90px;"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel m-b-10">
                            <div class="panel-heading" style="overflow: hidden">
                                Filter
                            </div>
                            <div style="padding: 0 20px 20px 20px;">
                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Address</button>
                                    </div>
                                    <input class="form-control" v-model="address" />
                                </div>
                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Radius</button>
                                    </div>
                                    <input type="number"  class="form-control"  v-model="radius">
                                    <span class="input-group-addon">KM</span>
                                </div>
                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Room Type</button>
                                    </div>
                                    <select class="form-control" v-model="room_type">
                                        <option value="entire_home">entire_home</option>
                                        <option value="private_room">private_room</option>
                                        <option value="shared_room">shared_room</option>
                                    </select>
                                </div>

                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Bed Count</button>
                                    </div>
                                    <input type="number"  class="form-control" v-model="bed_count_min">
                                    <span class="input-group-addon">to</span>
                                    <input type="number"  class="form-control" v-model="bed_count_max">
                                </div>

                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Bedroom Count</button>
                                    </div>
                                    <input type="number"  class="form-control" v-model="bedroom_count_min">
                                    <span class="input-group-addon">to</span>
                                    <input type="number"  class="form-control" v-model="bedroom_count_max">
                                </div>

                                <div class="input-group m-b-10">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn waves-effect waves-light btn-info dropdown-toggle">Guest Max Number</button>
                                    </div>
                                    <input type="number"  class="form-control" v-model="person_capacity_min">
                                    <span class="input-group-addon">to</span>
                                    <input type="number"  class="form-control" v-model="person_capacity_max">
                                </div>

                            </div>
                            <div class="panel-footer p-10" style="overflow: hidden;">
                                <button class="btn btn-success pull-right" @click="_getRooms">Go</button>
                            </div>
                        </div>
                        <div class="panel" style="position: relative">
                            <div id="map" style="height: 1200px;">
                                <loading :show="loadingMap"></loading>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Loading from '@/components/widgets/Loading'
    import Chart from '@/components/widgets/Chart/Chart'
    import {overview, rooms} from '@/api/bigdata'

    window.map = null
    window.center = null
    window.initMap = function initMap() {
        window.centerLat = center ? center.lat : 35.72
        window.centerLng = center ? center.lng : 139.76
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: new google.maps.LatLng( window.centerLat, window.centerLng),
            mapTypeId: 'roadmap'
        });

        // Create a <script> tag and set the USGS URL as the source.
        //var script = document.createElement('script');
        // This example uses a local copy of the GeoJSON stored at
        // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
        // script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
        // document.getElementsByTagName('head')[0].appendChild(script);

    }

    export default {
        name: "Overview",
        components: {Loading, Chart},
        mounted() {
            this.loading = true
            overview().then(res => {
                this.loading = false
                this.MarketGrade.RentalDemand = (res.data.rental_demand).toFixed(2) + '%'
                this.MarketGrade.RevenueGrowth = (res.data.revenue_growth).toFixed(2) + '%'
                this.MarketGrade.Seasonality = (res.data.seasonality).toFixed(2) + '%'
                this.MarketGrade.bookingLeadsTime = parseInt(res.data.booking_leads_time)
                this.AverageDailyRate = res.data.avg_daily_rate.toFixed(2)
                this.AccupancyRate = res.data.occupancy_rate.toFixed(2)
                this.Revence = res.data.revenue.toFixed(2)

                this.ActiveHost.total = res.data.super_host + res.data.single_listing_host
                this.ActiveHost.y = [{
                    name: 'Active Hosts',
                    data: [res.data.super_host, res.data.single_listing_host, res.data.multi_listing_host]
                }]

                let tmp = {
                    'type': 'pie',
                    'name': '物理房源类型占比',
                    'data': []
                }
                for (let key in res.data.rental_type) {
                    if (key === 'entire_home') {
                        tmp.data.push({
                            name: key,
                            y: res.data.rental_type[key],
                            sliced: true,
                            selected: true
                        },)
                    } else {
                        tmp.data.push([key, res.data.rental_type[key]])
                    }
                }
                this.ActiveRental.data = [tmp]

                let rental_size = []
                for (let key in res.data.rental_size) {
                    rental_size.push(res.data.rental_size[key])
                }

                this.RentalSize.y = [{
                    'name': 'Rooms',
                    data: rental_size,
                }]

            }).catch(e => {
                this.loading = false
            })
            this._getRooms()
        },
        data() {
            return {
                loading: false,
                loadingMap: false,
                MarketGrade: {
                    bookingLeadsTime: 0,
                    RentalDemand: 0,
                    RevenueGrowth: 0,
                    Seasonality: 0,
                },
                AverageDailyRate: 0,
                AccupancyRate: 0,
                Revence: 0,
                ActiveRental:  {
                    "entire_home": 0,
                    "private_room": 0,
                    "shared_room": 0,
                },
                RentalSize: {
                    x: ['1bedroom', "2bedroom", "3bedroom", "others", "studio"],
                    y: [{
                        name: 'Rooms',
                        data: [0, 0, 0, 0, 0]
                    }]
                },
                ActiveHost: {
                    y: [
                        {
                            name: 'Active Host',
                            data: [0, 0, 0]
                        }
                    ],
                    total: 0
                },
                center: null,
                address: '',
                radius: "",
                room_type: '',
                person_capacity_min: "",
                person_capacity_max: "",
                bedroom_count_min: "",
                bedroom_count_max: "",
                bed_count_min: "",
                bed_count_max: "",

                rooms: []
            }
        },
        methods: {
            genMap() {
                const s = document.createElement('script');
                s.type = 'text/javascript';
                s.src = 'https://maps.google.com/maps/api/js?region=ja&key=AIzaSyCSw_TUZrLAfOBklRsJwxpjQCozTGGgNtk&callback=initMap';
                document.body.appendChild(s);
                s.onload = function () {
                    this.infoWindow = new google.maps.InfoWindow({});
                    this.eqfeed_callback(this.rooms)
                }.bind(this)

                s.onerror = function (e) {

                }.bind(this)
            },
            _getRooms() {
                center = null
                this.loadingMap = true
                let params = {}

                if (this.address.trim().length) {
                    params.address = this.address
                }

                if (this.radius) {
                    params.radius = parseFloat(this.radius)
                }

                if (this.room_type) {
                    params.room_type = this.room_type
                }

                if (this.bed_count_min && this.bed_count_max) {
                    params.bed_count = [parseInt(this.bed_count_min), parseInt(this.bed_count_max)]
                }

                if (this.bedroom_count_min && this.bedroom_count_max) {
                    params.bedroom_count = [parseInt(this.bedroom_count_min), parseInt(this.bedroom_count_max)]
                }

                if (this.person_capacity_min && this.person_capacity_max) {
                    params.person_capacity = [parseInt(this.person_capacity_min), parseInt(this.person_capacity_max)]
                }

                rooms(params).then(res => {
                    this.loadingMap = false
                    center = {}
                    center.lat = res.data.base_lat
                    center.lng = res.data.base_lng
                    this.rooms = res.data.listings
                    if (map) {
                        initMap()
                        this.eqfeed_callback(this.rooms)
                    } else {
                        this.genMap()
                    }

                })

            },
            eqfeed_callback(rooms) {

                // centerMaker
                let marker = new google.maps.Marker({
                    position: {lat: centerLat, lng: centerLng},
                });
                marker.setMap(map);
                for (let i = 0; i < rooms.length; i++) {
                    let icon = rooms[i].room_type === 'private_room' ?
                        'https://manage.funkey.asia/upload/company/private_room.png' : rooms[i].room_type === 'shared_room' ?
                            'https://manage.funkey.asia/upload/company/shared_room.png' : 'https://manage.funkey.asia/upload/company/entire_home.png'
                    let lat = rooms[i].lat;
                    let lng = rooms[i].lng;
                    //let latLng = new google.maps.LatLng(lat, lng);
                    let marker = new google.maps.Marker({
                        position: {lat: lat, lng: lng},
                        icon: icon
                    });
                    marker.setMap(map);
                    // 使用闭包才能使变量marker保存
                    ((marker, data) => {
                        marker.addListener('click', () => {
                            this.infoWindow.setContent(this.setContent(data))
                            this.infoWindow.open(map, marker);
                        })

                    })(marker, rooms[i]);

                }
            },
            setContent(data) {
                let contentString = '<div id="content">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<h1 style="font-size: 20px;margin-bottom: 0;" id="firstHeading" class="firstHeading">' + data.title + '</h1>' +
                    '<div id="bodyContent">' +
                    '<p>' +
                    '<span class="m-r-10"><i class="fif fif-home text-info m-r-5"></i><span>' + data.room_type +'</span></span>' +
                    '<span class="m-r-10"><i class="fif fif-bed text-primary m-r-5"></i><span>' + data.bed_count +'</span></span>' +
                    '<span class="m-r-10"><i class="fif fif-bedroom text-warning m-r-5"></i><span>' + data.bedroom_count +'</span></span>' +
                    '<span class="m-r-10"><i class="fif fif-other-expense text-danger m-r-5"></i><span>' + data.base_fee +'</span></span>' +
                    '</p>' +
                    '</div>' +
                    '</div>';

                return contentString;
            },
        }
    }
</script>

<style scoped lang="stylus">

</style>